<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Backend\StoreAdmin;
use App\Http\Resources\Backend\AdminResource;
use App\Models\Admin;
use App\Models\AdminLog;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;

/**
 * Class AdminController
 * @package App\Http\Controllers\Backend
 * 管理员
 */
class AdminController extends BackendController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $admin = Admin::orderBy('created_at','desc')
            ->usernameLike($request->username)
            ->with('roles')
            ->paginate($request->size);
        return AdminResource::collection($admin);
    }

    /**
     * @param StoreAdmin $request
     * @return AdminResource|array
     */
    public function store(StoreAdmin $request)
    {
        $admin = Admin::create($request->all());
        $roles = Role::whereIn('id', $request->roles)->get();
        $admin->syncRoles($roles);
        AdminLog::Log("新增管理员: " . $admin->username);
        return new AdminResource($admin);
    }

    /**
     * @param Admin $admin
     * @return AdminResource
     */
    public function update(Admin $admin)
    {
        $admin->status = \request()->status;
        $admin->save();
        $roles = Role::whereIn('id',\request()->roles)->get();
        $admin->syncRoles($roles);
        AdminLog::Log("编辑管理员: " . $admin->username);
        return new AdminResource($admin);
    }

    /**
     * @param Admin $admin
     * @return AdminResource
     */
    public function destroy(Admin $admin)
    {
        $admin->password = '123456';
        $admin->save();
        AdminLog::Log('重置密码: ' . $admin->username);
        return new AdminResource($admin);
    }
}
